package com.communal.service.impl;

import java.util.ArrayList;
import java.util.Collection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.communal.dao.IUserDao;
import com.communal.model.User;
import com.communal.service.IAuthService;
import com.communal.util.AppConstants;

/**
 * Implements operation for user authorization. Needs for spring-security framework implementation
 * @author Created by andrey.kuznetsov <br>
 * @author Last modified by $Author$ <br>
 * @author Last modified on $Date$ at revision $Revision$ <br>
 */
@Service("userDetailsService")
public class AuthService extends AbstractService implements IAuthService, UserDetailsService{
	
	@Autowired 
	private IUserDao userDao;
	
	@Override
	@Transactional(readOnly=true)
	public UserDetails loadUserByUsername(String p_login) throws UsernameNotFoundException, DataAccessException {
		
		User userDB = userDao.getUserByLogin( p_login );
		if(userDB == null){
			throw new UsernameNotFoundException( "user not found" );
		}
		String username = userDB.getLogin();
	    String password = userDB.getPassword();
	    boolean enabled = userDB.getEnabled().equals( AppConstants.ENTITY_STATE_ENABLED )? true : false;
	    boolean accountNonExpired = enabled;
	    boolean credentialsNonExpired = enabled;
	    boolean accountNonLocked = enabled;

	    Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(); 
	    authorities.add(new GrantedAuthorityImpl(userDB.getRole().getName()));
	   
	    return new org.springframework.security.core.userdetails.User(username, password, enabled,
	  	      accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
	}

	
}
